<template>
  <el-config-provider :locale="zhCn">
    <div class="app-container material" h-full>
      <el-card shadow="never" relative h-full>
        <el-container h-full>
          <!-- 左侧分组 -->
          <el-card v-show="foldOpen" h-full class="sidebar-card">
            <MaterialGroup
              :material-type="materialType"
              :use-type="useType"
              :material-a-p-i="materialAPI"
              :t="t"
              @handle-material-group-list="updateMaterialGroupList"
              @select-material-group="selectMaterialGroup"
            />
          </el-card>

          <!-- 右侧主内容 -->
          <el-main>
            <!-- 工具栏 -->
            <div class="material-toolbar leading-10">
              <div class="flex material-toolbar-row">
                <div @click="handleFold">
                  <el-button v-if="foldOpen" icon="Fold" size="large" />
                  <el-button v-else icon="Expand" size="large" />
                </div>
                <div class="w-24 ml-1 mr-1">
                  <el-button
                    type="primary"
                    icon="Plus"
                    size="large"
                    @click="addMaterial"
                  >
                    {{ t("common.add") }}
                  </el-button>
                </div>

                <!-- 素材类型标签页 (仅在会话素材时显示) -->
                <el-tabs
                  v-if="showTabs"
                  v-model="materialType"
                  type="card"
                  @tab-click="handleTabClick"
                >
                  <el-tab-pane
                    :label="t('common.text')"
                    :name="MaterialType.TEXT"
                  />
                  <el-tab-pane
                    :label="t('common.image')"
                    :name="MaterialType.IMAGE"
                  />
                  <el-tab-pane
                    :label="t('common.video')"
                    :name="MaterialType.VIDEO"
                  />
                  <el-tab-pane
                    :label="t('common.voice')"
                    :name="MaterialType.AUDIO"
                  />
                  <el-tab-pane
                    :label="t('common.sticker')"
                    :name="MaterialType.STICKER"
                  />
                  <el-tab-pane
                    :label="t('common.gif')"
                    :name="MaterialType.GIF"
                  />
                  <el-tab-pane
                    :label="t('session.businessCard')"
                    :name="MaterialType.CARD"
                  />
                  <el-tab-pane
                    :label="t('common.file')"
                    :name="MaterialType.FILE"
                  />
                  <el-tab-pane
                    :label="t('common.link')"
                    :name="MaterialType.LINK"
                  />
                  <el-tab-pane
                    :label="t('common.imageTextTemplate')"
                    :name="MaterialType.IMAGETEXTTEMPLATE"
                  />
                  <el-tab-pane
                    :label="t('message.type.poll')"
                    :name="MaterialType.POLL"
                  />
                  <template v-if="useType === 1">
                    <el-tab-pane
                      :label="t('common.forwardHyperlink')"
                      :name="MaterialType.MERCHANT_LINK"
                    />
                  </template>
                </el-tabs>
                <div class="ml-auto flex items-center">
                  <el-tooltip
                    effect="dark"
                    :content="t('common.refresh')"
                    placement="top"
                  >
                    <div class="toolbar-refresh-icon" @click="refreshTable">
                      <el-icon>
                        <Refresh />
                      </el-icon>
                    </div>
                  </el-tooltip>
                </div>
              </div>
            </div>

            <!-- 素材表格 -->
            <MaterialTable
              ref="materialTableRef"
              :group-id="materialGroupId"
              :type="materialType"
              :use-type="useType"
              :material-a-p-i="materialAPI"
              :material-group-list="materialGroupList"
              :upload-status="uploadStatus"
              :simple-mode="simpleMode"
              :t="t"
            />
          </el-main>
        </el-container>
      </el-card>

      <!-- 添加素材对话框 -->
      <AddMaterial
        :use-type="useType"
        :material-type="materialType"
        :material-group-list="materialGroupList"
        :add-material-visible="addMaterialVisible"
        :material-a-p-i="materialAPI"
        :upload-handler="uploadHandler"
        :t="t"
        @update:add-material-visible="addMaterialVisible = $event"
        @material-added="handleMaterialAdded"
      />
    </div>
  </el-config-provider>
</template>

<script lang="ts" setup>
import { ref, computed, type PropType } from "vue";
import {
  ElCard,
  ElContainer,
  ElMain,
  ElButton,
  ElTabs,
  ElTabPane,
  ElTooltip,
  ElIcon,
} from "element-plus";
// 确保在直接引用单文件组件时也能加载 Element Plus 基础样式
import "element-plus/dist/index.css";
import { ElConfigProvider } from "element-plus";
import zhCn from "element-plus/es/locale/lang/zh-cn";
import { Refresh } from "@element-plus/icons-vue";
import { MaterialType } from "./types/index";
import type { MaterialAPI } from "./api/index";
import MaterialGroup from "./MaterialGroup.vue";
import MaterialTable from "./MaterialTable.vue";
import AddMaterial from "./AddMaterial.vue";

// 定义属性
const props = defineProps({
  // 素材类型 (avatar, nickname, about, session, feeding)
  mode: {
    type: String as PropType<
      "avatar" | "nickname" | "about" | "session" | "feeding"
    >,
    default: "session",
  },
  // 使用类型 1业务 2养号
  useType: {
    type: Number,
    default: 1,
  },
  // 初始素材类型
  initialMaterialType: {
    type: String,
    default: MaterialType.TEXT,
  },
  // 素材API实例
  materialAPI: {
    type: Object as PropType<MaterialAPI>,
    required: true,
  },
  // 文件上传处理函数
  uploadHandler: {
    type: Function,
    default: null,
  },
  // 翻译函数
  t: {
    type: Function as PropType<(key: string) => string>,
    required: true,
  },
  // 简洁模式：仅显示内容和操作列
  simpleMode: {
    type: Boolean,
    default: false,
  },
});

// 定义事件
const emit = defineEmits<{
  (e: "materialAdded"): void;
}>();

// 响应式数据
const materialType = ref<string>(getMaterialTypeByMode());
const addMaterialVisible = ref<boolean>(false);
const materialGroupId = ref<string>();
const materialGroupList = ref([]);
const foldOpen = ref<boolean>(true);
const uploadStatus = ref<boolean>(false);
const materialTableRef = ref<any>();

// 默认翻译函数
const t = props.t;

// 计算属性
const showTabs = computed(() => {
  return props.mode === "session" || props.mode === "feeding";
});

// 根据模式获取初始素材类型
function getMaterialTypeByMode(): string {
  switch (props.mode) {
    case "avatar":
      return MaterialType.AVATAR;
    case "nickname":
      return MaterialType.NICKNAME;
    case "about":
      return MaterialType.SIGNATURE;
    case "feeding":
    case "session":
    default:
      return props.initialMaterialType || MaterialType.TEXT;
  }
}

// 方法定义
const handleFold = () => {
  foldOpen.value = !foldOpen.value;
};

const handleTabClick = async (tab: any) => {
  materialType.value = tab.props.name;
};

const updateMaterialGroupList = (list: any) => {
  materialGroupList.value = list;
};

const selectMaterialGroup = (groupId: string) => {
  materialGroupId.value = groupId;
};

const addMaterial = () => {
  addMaterialVisible.value = true;
};

const handleMaterialAdded = () => {
  uploadStatus.value = false;
  emit("materialAdded");
};

// 工具栏刷新动作：调用子表格的公开刷新方法
const refreshTable = () => {
  try {
    materialTableRef.value?.tableDataList?.();
  } catch (e) {
    // no-op
  }
};
</script>

<style lang="scss">
.material {
  height: 100%;
  overflow: hidden; /* 防止外层滚动 */
  padding: 24px; /* 增加 app-container 的内边距 */
}

.material > .el-card {
  height: 100%;
  overflow: hidden;
}

.material > .el-card > .el-card__body {
  height: 100%;
  overflow: hidden;
  padding: 24px; /* 增加外层 card 的内边距 */
}

.material .el-container {
  display: flex;
  height: 100%;
  gap: 16px;
  overflow: hidden; /* 防止容器滚动 */
}

/* 左侧分组卡片固定宽度，高度撑满 */
.material .sidebar-card {
  width: 280px;
  min-width: 280px;
  max-width: 280px;
  flex: 0 0 280px;
  height: 100%;
  display: flex;
  overflow: hidden;
}

.material .sidebar-card .el-card__body {
  height: 100%;
  overflow-y: auto; /* 只有分组内部可以滚动 */
}

.material .el-main {
  flex: 1 1 auto;
  display: flex;
  flex-direction: column;
  padding: 0; /* 去掉 main 的 padding，因为外层已经有了 */
  min-height: 0; /* 关键：允许 flex 子元素缩小 */
  overflow: hidden; /* 防止 main 区域滚动 */
}

/* 工具栏行：与 Tabs 垂直居中，间距一致 */
.material .material-toolbar {
  flex: 0 0 auto; /* 固定高度，不参与 flex 缩放 */
  margin-bottom: 16px; /* 与表格的间距 */
  padding-top: 0; /* 顶部不需要额外 padding */
}

.material .material-toolbar.leading-10 {
  line-height: 2.5rem; /* 40px */
}

.material .material-toolbar > .flex.material-toolbar-row {
  align-items: center;
  gap: 8px;
  min-height: 40px; /* 对齐 Tabs 高度 */
}

/* 让标签页占据剩余空间，避免换行到下一行 */
.material .material-toolbar .el-tabs {
  flex: 1 1 auto;
  margin-left: 8px;
  min-width: 0;
}

/* 防止标签换行，允许横向滚动 */
.material .material-toolbar .el-tabs__nav-wrap {
  overflow-x: auto;
  overflow-y: hidden;
}

.material .material-toolbar .el-tabs__nav-scroll {
  display: flex;
  white-space: nowrap;
}

/* 刷新按钮容器 */
.material .material-toolbar .ml-auto {
  margin-left: auto;
  padding-left: 16px;
}

.material .material-toolbar .flex.items-center {
  display: flex;
  align-items: center;
}

/* 去掉 Tabs 头部额外间距并统一高度 */
.material .material-toolbar .el-tabs__header {
  margin: 0;
}
.material .material-toolbar .el-tabs__item {
  height: 40px;
  line-height: 40px;
}

/* 保证标签横向排列（防止样式缺失时出现纵向堆叠） */
.material .el-tabs__nav {
  display: flex;
  flex-direction: row;
  flex-wrap: nowrap;
}

/* 确保每个标签项不换行 */
.material .material-toolbar .el-tabs__item {
  flex-shrink: 0;
  white-space: nowrap;
}

/* 表格区域填满剩余高度，内部滚动 */
.material .material-table {
  flex: 1 1 auto;
  min-height: 0; /* 关键：允许表格容器缩小 */
  overflow: hidden; /* 表格自己处理滚动 */
}

/* 工具栏刷新图标样式 */
.toolbar-refresh-icon {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 32px;
  height: 32px;
  border: 1px solid #dcdfe6;
  border-radius: 50%;
  transition: all 0.3s;
  background-color: var(--el-bg-color);
  cursor: pointer;
  font-size: 16px;

  &:hover {
    background-color: var(--el-bg-color-page);
    border-color: var(--el-color-primary);
  }
}
</style>
